$(function() {
	var rows_delete=0;
	var mode="add";
	var m_id=0;
    var url='controls/employee_model.php';
	if (_dd==1){
		$("#btnAdd").show();
	}else{
		$("#btnAdd").hide();
	}
	
	$("#btnPrintDraft").click(function(){
	  $("#resultData").printThis();
		return false;
           
	});	
	
    var checkDate = $('#txtDateIn').datepicker().on('changeDate', function(ev) {
	  checkDate.hide();
	}).data('datepicker');
	 
	LoadData('','',0,0,'');
	 
	$("#txtSalary").keypress(function(e){
		
		if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)){
			return false;
		}
	});
	
	 function LoadData(code,name,sid,did,id){
		BlockUI();
        $( "#resultData tbody tr" ).remove();
 
        
        $('#resultData').dataTable( {
			"bProcessing": true,
			"bFilter": false,
			"bLengthChange": false,
			 "bAutoWidth": false,
			"sAjaxSource": url,
			"oLanguage": {
				"sEmptyTable":     "ไม่พบข้อมูล"
			},
			"bDestroy": true,
			"sServerMethod": "POST",
			"fnServerParams": function ( aoData ) {
					aoData.push( { "name": "m", "value": "load" },
								{"name":"code","value":code},
								{"name":"name","value":name},
								{"name":"status","value":sid},
								{"name":"depart","value":did},
								{"name":"idcard","value":id}
							);
				},
			"aoColumnDefs":[
				{  "bVisible": false , "aTargets": [ 1 ] },	
				{  "bSortable": true , "aTargets": [ 2 ] ,"sClass":"text-center" },	
			 	{  "bSortable": true , "aTargets": [ 3 ] ,"sClass":"center" },	
				{   "bSortable": true, "aTargets": [ 4 ] ,"sClass":"alignLeft"},	
				{   "bSortable": true, "aTargets": [ 5 ] ,"sClass":"alignLeft" },	
				{   "bSortable": true, "aTargets": [ 6 ] ,"sClass":"alignLeft" },	
				{    "bSortable": true,"aTargets": [ 7 ]
					, "sClass":"center"
					, "mData": null,
					"mRender": function ( data, type, full ) {
						if (full[11]=='1')
						return "<font color='red'>" + full[7] +"</font>";
						else
						return "<font color='green'>" + full[7] +"</font>";;
					}
				},
				{  "bVisible": false , "aTargets": [ 8 ] },	 //address
				{  "bVisible": false , "aTargets": [ 9 ] },	   //education
				{  "bVisible": false , "aTargets": [ 10 ] },	  //did
				{  "bVisible": false , "aTargets": [ 11 ] },	  // status
				{  "bVisible": false , "aTargets": [ 12 ] },	 //title id
				{  "bVisible": false , "aTargets": [ 13 ] },	 //date in 
				{  "bVisible": false , "aTargets": [ 14 ] },	 //name 
				{  "bVisible": false , "aTargets": [ 15 ] },	 //salary
				{  "bVisible": false , "aTargets": [ 16 ] },	 //account
				{  "bVisible": false , "aTargets": [ 17 ] },	 //course fee
				{ "aTargets": [ 18 ],
					"sClass":"center",
					"mData": null,
					"mRender": function ( data, type, full ) {
						if (_it==1)
						return "<a href='#popup' data-toggle='modal'><img src='img/edit-file.png' class='btnEdit' style='cursor:pointer;'/></a>";
						else
						return "";
					}
				},
				{"aTargets": [ 19 ],
					"sClass":"center",
					"mData": null,
					"mRender": function ( data, type, full ) {
						if (_te==1)
						return "<a href='#popupConfirm' data-toggle='modal'><img src='img/delete-file.png' class='btnDel' style='cursor:pointer;'/></a>";
						else
							return "";
					}
				}
			],"fnDrawCallback": function ( oSettings ) {
				 var that = this;
				/* Need to redo the counters if filtered or sorted */
                 var iTotalRecords = oSettings.fnRecordsTotal();
				//alert(oSettings.aiDisplay.length + ' ' + iTotalRecords);
				 
					if (iTotalRecords > 0){ 	
						if ( oSettings.bSorted || oSettings.bFiltered )
						{
							for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ )
							{
								$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
							}
						}
					}
					setTimeout(function(){$.unblockUI();},1500);
				} 
		 } );
		 
      }
 
	$.get(url, {"m":"dy"},function(data){
			var obj=eval('('+data+')');	
			if (obj != null){
				$.each(obj, function(index, text) {
					$("#cboDepartment").append(
							$('<option></option>').val(text).html(index)
						 );
				});
			}
	});
	$.get(url, {"m":"gy"},function(data){
			var obj=eval('('+data+')');	
			if (obj != null){
				$.each(obj, function(index, text) {
					$("#cboStatus").append(
							$('<option></option>').val(text).html(index)
						 );
				});
			}
	});
	
	$.get(url, {"m":"g"},function(data){
			var obj=eval('('+data+')');	
			if (obj != null){
				$.each(obj, function(index, text) {
					$("#cboStatus_s").append(
							$('<option></option>').val(text).html(index)
						 );
				});
			}
	});
	$("#cboStatus_s").append($('<option></option>').val(0).html(' ' ));
	$.get(url, {"m":"d"},function(data){
			var obj=eval('('+data+')');	
			if (obj != null){
				$.each(obj, function(index, text) {
					$("#cboDepartment_s").append(
							$('<option></option>').val(text).html(index)
						 );
				});
			}
	});
	$("#cboDepartment_s").append($('<option></option>').val(0).html(' '));
	
	
	$("#btnSearch").click(function(){
		var _code = $("#txtCode_s").val();
		var _name = $("#txtName_s").val();
		var _sid = $("#cboStatus_s").val();
		var _did = $("#cboDepartment_s").val();
		var _id = $("#txtId_s").val();
		 
		LoadData(_code,_name,_sid,_did,_id);
	});
	
	 
	
	$("#btnSave").live('click',function(){
		$("input").not("[type=submit]").jqBootstrapValidation({preventSubmit: false,
			submitSuccess: function ($form, event) { event.preventDefault();}
		}); 
		
		var _code = $.trim($("#txtCode").val());		
		var _name = $.trim($("#txtEmployeeName").val());		
		var _title = $.trim($("#cboTitle").val());		
		var _datein = $("#txtDateIn").val();
		var _id = $("#txtIDCard").val();
		var _did = $("#cboDepartment").val();
		var _sid = $("#cboStatus").val();
		var _salary = $("#txtSalary").val();
		var _education = $("#txtEducation").val();
		var _tele = $("#txtTelephone").val();
		var _address = $("#txtAddress").val();
		var _account =$("#txtAccount").val();
		var _cost_fee=$("#txtCost_Fee").val();
		var dataSet;
		 
		if (mode=="add"){
			dataSet={"m":"add","code":_code,"id_card":_id,"account":_account,"salary":_salary,"name":_name,"date_in": _datein,"title":_title,"address":_address,"status":_sid,"course_fee":_cost_fee,"tele":_tele,"education":_education,"department":_did};  
		}else{
			dataSet={"m":"edit","id":m_id,"id_card":_id,"account":_account,"salary":_salary,"code":_code,"name":_name,"date_in": _datein,"title":_title,"address":_address,"course_fee":_cost_fee,"status":_sid,"tele":_tele,"education":_education,"department":_did};   
		}
		if (_code!="" &&  _name!=""){
			$.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: dataSet,
				success: function(data){
				   if (data == 1){
						$("#popup").modal('hide');
					 LoadData('','',0,0);
					}else{
						alert("รหัสประจำตัวซ้ำ");
						$("#txtCode").focus();
					}
				}
			});
			
		}
		 $("input").jqBootstrapValidation("destroy");
	});		
	 
	$("#btnAdd").live('click', function(){
		mode="add";
		$("#txtEmployeeName").val("");
		 $("#txtCode").val("");
		 $("#txtIDCard").val("");
		 $("#txtTelephone").val("");
		 $("#txtAccount").val("");
		 $("#txtDateIn").val("");
		 $("#txtCost_Fee").val("0");
		  $("#txtSalary").val("");
		 $("#txtAddress").val("");
		 $("#txtEducation").val("");
	});
		
	//Popup confirm delete
	$(".btnDel").live('click',function(){
		var rows = $(this).closest("tr").get(0);
		rows_delete = $('#resultData').dataTable().fnGetPosition(rows);

	}); 
	
	$("#btnDelete").live('click', function(){
		 
		var row_id =$('#resultData').dataTable().fnGetData(rows_delete);
		
		var id=row_id[1];
		 
		 $.ajax({
				 type: 'POST',
				 cache: false,
				 url: url,
				 data: {"m":"del","id":id},
				 success: function(data){
					$("#popupConfirm").modal('hide');
					
					$('#resultData').dataTable().fnDeleteRow( rows_delete );
					$('#resultData').dataTable().fnDraw();
				 }
			 });
 
	}); 
	
	$(".btnEdit").live('click',function(){
		mode="edit";
		var rows = $('#resultData').dataTable().fnGetPosition($(this).closest("tr").get(0));
		var data =$('#resultData').dataTable().fnGetData(rows);
		 
		m_id = data[1];
		 $("#txtEmployeeName").val(data[14]);
		 $("#txtIDCard").val(data[2]); 
		 $("#txtCode").val(data[3]);	
		 $("#cboDepartment").val(data[10]);
		 $("#txtTelephone").val(data[6]);
		 $("#cboTitle").val(data[12]);
		 $("#txtDateIn").val(data[13]);
		 $("#cboStatus").val(data[11]); 
		  $("#txtSalary").val(data[15]);
		  $("#txtAccount").val(data[16]);
		 $("#txtAddress").val(data[8]);
		 $("#txtEducation").val(data[9]);
		 $("#txtCost_Fee").val(data[17]);
	 
	});
	  
    
});


